import Taro from "@tarojs/taro";
// import QS from 'qs'
import qs from "qs";
import {
  getStorage,
  clearStorage,
  getCurrentPageUrlWithArgs,
} from "..//utils/tools";
import { useUserStore } from "../store";
let needLoadingRequestCount = 0;
// loading配置，请求次数统计
function startLoading() {
  Taro.showLoading({ title: "加载中", mask: true });
}
function endLoading() {
  Taro.hideLoading();
} // 声明一个对象用于存储请求个数
function showFullScreenLoading() {
  if (needLoadingRequestCount === 0) {
    startLoading();
  }
  needLoadingRequestCount++;
}
function tryHideFullScreenLoading() {
  if (needLoadingRequestCount <= 0) return;
  needLoadingRequestCount--;
  if (needLoadingRequestCount === 0) {
    endLoading();
  }
}
//loading是做了多个请求同时发起的时候防止动画叠加

export default function request(url, config: any = {}, needLoading = false) {
  // const BASE_URL = "http://192.168.110.171:5102";
  const BASE_URL = config.BASE_URL || "http://business-api.liangpiao.net.cn";
  // const BASE_URL =  config.BASE_URL || "http://test-consume-api.liangpiaovip.com";

  // const BASE_URL = "http://k8s-cluster.liangpiaovip.com:30080/liangpiao-consume";

  //默认加载都带动画设置false不加载
  const userStore = useUserStore();
  needLoading && showFullScreenLoading();
  return new Promise((resolve, reject) => {
    Taro.request({
      url: `${BASE_URL}${url}`,
      method: config.type.toUpperCase() || "GET",
      data: config.data || {},
      timeout: 20000,
      header: {
        "Content-type": config.paramsFormdata || "application/json",
        "user-token": userStore.Token || "",
        ...config.header,
      },

      success: (result: any) => {
        const { statusCode, data } = result;
        if (statusCode === 200) {
          if (result?.token) {
            Taro.setStorageSync("TOKEN", result?.token);
          }
          resolve(data);
        } else if (statusCode === 401) {
          Taro.removeStorageSync("TOKEN");
          Taro.removeStorageSync("userInfo");
          setTimeout(() => {
            if (window.location.href.indexOf("/pages/login/index") == -1) {
              Taro.redirectTo({
                url: "/pages/login/index",
              });
            }
          }, 500);
        }
      },
      fail: (error) => {
        Taro.showToast({
          title: "网络错误",
          icon: "error",
        });
        return error;
      },
      complete: (res) => {
        // tryHideFullScreenLoading();
      },
    });
  });
}
